#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <atomic>
#include <future>

class ThreadPool
{
public:
    static ThreadPool* GetInstance(size_t numThreads = 4)
    {
        static ThreadPool _pool(numThreads);
        return &_pool;
    }
    ThreadPool(ThreadPool const&) =delete;
    ThreadPool& operator=(ThreadPool const&)=delete;

private:
    ThreadPool(size_t numThreads) : stop(false)
    {
        for (size_t i = 0; i < numThreads; i++)
        {
            workers.emplace_back([this]()
                                 {
                //每个线程要不断地从任务队列中拿任务并且执行
                while(true)
                {
                    std::function<void()> task;
                    {
                        std::unique_lock<std::mutex> lock(this->queueMutex);
                        this->condition.wait(lock,[this]()
                        {
                            return this->stop || !tasks.empty(); //终止线程池或者任务队列有任务就停止等待
                        });

                        if(this->stop && tasks.empty()) break; //如果线程池终止并且任务队列无任务就退出
                        //走到这线程池属于运行态并且有任务
                        task=std::move(this->tasks.front());
                        this->tasks.pop();
                    }
                    task();
                } });
        }
    }
public:
    ~ThreadPool()
    {
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            stop = true;
        }
        // 唤醒所有线程,让他们执行完任务并退出
        condition.notify_all();
        // 等待所有线程退出
        for (auto &t : workers)
        {
            t.join();
        }
    }

    // void Enqueue(std::function<void()> task)
    // {
    //     {
    //         std::unique_lock<std::mutex> lock(queueMutex);
    //         tasks.push(task);
    //     }
    //     condition.notify_one(); // 唤醒一个工作线程
    // }

    template<class F,class... Args>
    auto enqueue(F&& f,Args&&... args)-> std::future<typename std::result_of<F(Args...)>::type>
    {
        using returnType=typename std::result_of<F(Args...)>::type;
        auto task=std::make_shared<std::packaged_task<returnType()>>(std::bind(std::forward<F>(f),std::forward<Args>(args)...));
        std::future<returnType> res=task->get_future(); //返回值占位符
        {
            std::unique_lock<std::mutex> lock(queueMutex);
            tasks.emplace([task](){(*task)();});
        }
        condition.notify_one();
        return res;
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;
    std::mutex queueMutex;
    std::condition_variable condition;
    std::atomic<bool> stop;
};

int main()
{
    auto tp=ThreadPool::GetInstance(4);
    auto task1=tp->enqueue([]()
    {
        std::cout<<"Task 1 is running"<<std::endl;
    });
    auto task2=tp->enqueue([](int a,int b)
    {
        std::cout << "Task 2 result: " << (a + b) << std::endl;
        return a+b;
    },5, 10);
    task1.get();
    std::cout<<"Task 2 return: " <<task2.get() <<std::endl;
    return 0;
}